/*
 *  Axolotl - Alternate persistence for Grails
 *  Copyright (C) 2008  Juanjo García Latre
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package com.googlecode.axolotl.lazy;

import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.target.AbstractLazyCreationTargetSource;

import com.googlecode.axolotl.Database;


public abstract class LazyEntity {

	public static Object create(Class targetClass, Object identifier, Database database) {
		return ProxyFactory.getProxy( new EntityTargetSource(targetClass, identifier, database) );
	}
	
	
	public static boolean isLazy(Object entity) {
		return entity instanceof Advised && 
				((Advised) entity).getTargetSource() instanceof EntityTargetSource;
	}

	
	public static Object getId(Object entity) {
		EntityTargetSource targetSource = (EntityTargetSource) ((Advised) entity).getTargetSource();
		return targetSource.id;
	}
	
	
	public static Class getClass(Object entity) {
		EntityTargetSource targetSource = (EntityTargetSource) ((Advised) entity).getTargetSource();
		return targetSource.clazz;
	}

	
	private static class EntityTargetSource extends AbstractLazyCreationTargetSource {
		private final Class clazz;
		private final Object id;
		private final Database database;
		
		public EntityTargetSource(Class clazz, Object id, Database database) {
			this.clazz = clazz;
			this.id = id;
			this.database = database;
		}

		@Override
		public synchronized Class getTargetClass() {
			return clazz;
		}	

		@Override
		protected Object createObject() throws Exception {
			return database.load(clazz, id);
		}	
	}
}
